<script setup>
import { admincreateCarousel } from '@/api/carouse'
import { useUserStore } from '@/stores'
import { PlusOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { ref } from 'vue'
const confirmLoading = ref(false)
const open = ref(false)
const emit = defineEmits(['submit-change'])
const handleOk = () => {
  confirmLoading.value = true
  setTimeout(() => {
    open.value = false
    confirmLoading.value = false
  }, 2000)
  open.value = false
}
const beforeUpload = (file) => {
  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('图片格式有误!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大小必须小于2MB!')
  }
  return isJpgOrPng && isLt2M
}
const userStore = useUserStore()
const carouselInfo = ref({
  title: '',
  imageUrl: '',
  linkUrl: '',
  sortorder: ''
})
const Submitcarousel = async () => {
  try {
    console.log(carouselInfo.value)
    if (carouselInfo.value.title === '') {
      message.error('请填写轮播图名称')
    } else if (carouselInfo.value.imageUrl === '') {
      message.error('请上传图片')
    } else if (carouselInfo.value.linkUrl === '') {
      message.error('请填写跳转连接')
    } else if (carouselInfo.value.sortorder === 0) {
      message.error('请填写轮播图顺序')
    }
    const res = await admincreateCarousel({
      title: carouselInfo.value.title,
      imageUrl: carouselInfo.value.imageUrl,
      linkUrl: carouselInfo.value.linkUrl,
      sortOrder: carouselInfo.value.sortorder // 确保属性名匹配
    })
    console.log(res)
    if (res) {
      if (res.data.code === 1) {
        message.success('轮播图添加成功')
        emit('submit-change')
        carouselInfo.value = {
          title: '',
          imageUrl: '',
          linkUrl: '',
          sortorder: '' // 保持为字符串类型，以便用户输入
        }
      } else {
        message.error('轮播图创建失败')
      }
    } else {
      message.error('未收到服务器响应')
    }
  } catch (error) {
    console.error('创建轮播图失败:', error)
    message.error('创建轮播图时发生错误')
  }
}
//string转number
const handleInput = (event) => {
  const value = event.target.value
  const numValue = value === '' ? '' : Number(value)
  if (!isNaN(numValue)) {
    carouselInfo.value.sortorder = numValue
  } else {
    carouselInfo.value.sortorder = ''
  }
}
const headers = {
  adminToken: userStore.token
}
const previewVisible = ref(false)
const previewImage = ref('')
const previewTitle = ref('')
const loading = ref(false)
const handleCancel = () => {
  previewVisible.value = false
  previewTitle.value = ''
}
const handlePreview = async (file) => {
  previewVisible.value = true
  previewTitle.value =
    file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
}
const handleChange = (info) => {
  if (info.file.status === 'done') {
    loading.value = false
    message.success(`${info.file.name} 文件上传成功！`)
    // 确保服务器返回的响应中包含了图片URL
    if (info.file.response && info.file.response.data) {
      // 假设URL在响应的data字段中
      carouselInfo.value.imageUrl = info.file.response.data
      previewImage.value = info.file.response.data
    } else {
      message.error('上传成功，但未获取到图片URL')
    }
  } else if (info.file.status === 'error') {
    loading.value = false
    message.error('上传失败！')
  }
}
const showModal = () => {
  open.value = true
}
defineExpose({ showModal })
</script>

<template>
  <a-modal
    v-model:open="previewVisible"
    title="图片预览"
    @cancel="handleCancel"
    @ok="handleCancel"
  >
    <img :src="previewImage" alt="预览图" style="width: 100%" />
  </a-modal>
  <a-modal
    v-model:open="open"
    title="请输入信息"
    @ok="handleOk"
    @cancel="handleCancel"
  >
    <h3>标题</h3>
    <a-input-group compact>
      <a-input v-model:value="carouselInfo.title" style="width: 50%" />
    </a-input-group>
    <h3>选择图片</h3>
    <a-form-item label="">
      <a-upload
        :headers="headers"
        action="/aPi/web/admin/common/upload"
        list-type="picture-card"
        :before-upload="beforeUpload"
        @preview="handlePreview"
        @change="handleChange"
      >
        <div>
          <PlusOutlined />
          <div style="margin-top: 8px">上传</div>
        </div>
      </a-upload>
    </a-form-item>
    <h3>顺序</h3>
    <a-input-group compact>
      <a-input
        @input="handleInput"
        v-model:value="carouselInfo.sortorder"
        style="width: 50%"
      />
    </a-input-group>
    <h3>跳转链接</h3>
    <a-input-group compact>
      <a-input v-model:value="carouselInfo.linkUrl" style="width: 50%" />
    </a-input-group>
    <br />
    <a-button
      type="primary"
      block
      size="middle"
      @click="Submitcarousel()"
      style="width: 18%"
    >
      添加
    </a-button>
  </a-modal>
</template>
